package com.mcxx.modules.extremepoverty.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSON;
import com.mcxx.common.exception.BizException;
import com.mcxx.modules.extremepoverty.service.ExSuspendManagementService;
import com.mcxx.modules.minimumliving.service.ExpireSalvationService;
import com.mcxx.modules.minimumliving.service.RecheckService;
import com.mcxx.modules.minimumliving.service.SalvationApplyService;
import com.mcxx.modules.base.service.read.SuspendFamilyReadService;
import com.mcxx.modules.base.utils.QueryParamUtil;
import com.mcxx.modules.miniSalvation.family.dto.BatchProtectResultDTO;
import com.mcxx.modules.miniSalvation.family.dto.SuspendFamilyResultDTO;
import com.mcxx.modules.miniSalvation.family.entity.FamilyMainHistoryEntity;
import com.mcxx.modules.miniSalvation.family.entity.FamilyMemberEntity;
import com.mcxx.modules.miniSalvation.family.entity.FamilyMemberHistoryEntity;
import com.mcxx.modules.miniSalvation.family.param.BatchProtectParam;
import com.mcxx.modules.miniSalvation.family.param.ExpireFamilyParam;
import com.mcxx.modules.miniSalvation.family.param.SuspendFamilyResultParam;
import com.mcxx.modules.miniSalvation.family.service.read.FamilyMainHistoryReadService;
import com.mcxx.modules.miniSalvation.family.service.read.FamilyMemberHistoryReadService;
import com.mcxx.modules.miniSalvation.family.service.read.FamilyMemberReadService;
import com.mcxx.modules.miniSalvation.family.service.write.FamilyMemberHistoryWriteService;
import com.mcxx.modules.miniSalvation.family.service.write.SuspendFamilyWriteService;
import com.mcxx.modules.miniSalvation.family.service.write.SuspendMemberWriteService;
import com.mcxx.modules.miniSalvation.fundpay.service.read.FundPayReadService;
import com.mcxx.modules.miniSalvation.order.dto.BatchExpireDTO;
import com.mcxx.modules.miniSalvation.order.entity.OrderEntity;
import com.mcxx.modules.miniSalvation.order.entity.SuspendApproveEntity;
import com.mcxx.modules.miniSalvation.order.entity.SuspendFamilyEntity;
import com.mcxx.modules.miniSalvation.order.event.SuspendManageEvent;
import com.mcxx.modules.miniSalvation.order.service.read.OrderReadService;
import com.mcxx.modules.miniSalvation.order.service.read.OrderSuspendCareReadService;
import com.mcxx.modules.miniSalvation.order.service.write.OrderWriteService;
import com.mcxx.modules.miniSalvation.order.service.write.SuspendApproveWriteService;
import com.mcxx.modules.miniSalvation.salary.entity.FamilySalaryEntity;
import com.mcxx.modules.miniSalvation.salary.entity.MemberSalaryEntity;
import com.mcxx.modules.miniSalvation.salary.service.read.FamilyMemberSalaryReadService;
import com.mcxx.modules.miniSalvation.salary.service.read.FamilySalaryReadService;
import com.mcxx.modules.miniSalvation.salary.service.write.*;
import com.mcxx.result.BaseResult;
import com.mcxx.util.CommonUtil;
import com.mcxx.util.Constant;
import com.mcxx.util.DateUtil;
import com.mcxx.util.FailureCode;
import com.yinhai.ta404.core.restservice.requestbean.PageParam;
import com.yinhai.ta404.core.restservice.resultbean.Page;
import com.yinhai.ta404.core.security.vo.UserAccountVo;
import com.yinhai.ta404.core.service.BaseService;
import com.yinhai.ta404.core.transaction.annotation.TaTransactional;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;


@Slf4j
@Service("exSuspendManagementService")
@TaTransactional
public class ExSuspendManagementServiceImpl extends BaseService implements ExSuspendManagementService {

    @Autowired
    private FamilyMemberHistoryWriteService familyMemberHistoryWriteService;
    @Autowired
    private FamilyMemberHistoryReadService familyMemberHistoryReadService;
    @Autowired
    private FamilyMemberSalaryReadService familyMemberSalaryReadService;
    @Autowired
    private FamilyMainHistoryReadService familyMainHistoryReadService;
    @Autowired
    private SuspendFamilyWriteService suspendFamilyWriteService;
    @Autowired
    private SuspendMemberWriteService suspendMemberWriteService;
    @Autowired
    private SalaryChangeWriteService salaryChangeWriteService;
    @Autowired
    private FamilyMemberSalaryWriteService familyMemberSalaryWriteService;
    @Autowired
    private SuspendFamilyReadService suspendFamilyReadService;
    @Autowired
    private FamilySalaryWriteService familySalaryWriteService;
    @Autowired
    private FamilySalaryReadService familySalaryReadService;
    @Autowired
    private FamilyMemberReadService familyMemberReadService;
    @Autowired
    private FundPayReadService fundPayReadService;
    @Autowired
    private OrderWriteService orderWriteService;
    @Autowired
    private OrderReadService orderReadService;
    @Autowired
    private ExpireSalvationService expireSalvationService;
    @Autowired
    private ApplicationContext applicationContext;
    @DateTimeFormat(pattern = "yyyyMM")
    private LocalDateTime dateTime;
    @Autowired
    private SuspendApproveWriteService suspendApproveWriteService;
    @Autowired
    private RecheckService recheckService;
    @Autowired
    private SalvationApplyService salvationApplyService;
    @Autowired
    private OrderSuspendCareReadService orderSuspendCareReadService;

    @Override
    public Page queryZanTingList(BatchProtectParam param, UserAccountVo userAccountVo, PageParam pageParam) {
        Page<BatchProtectResultDTO> page = new Page<>();
//        param.setTokenAreaCode(QueryParamUtil.setAreaCodeByLevel(userAccountVo.getAreaCode(),
//                Integer.valueOf(userAccountVo.getAreaLevel())));
//        param.setAddressCode(setAdressParam(param.getAddressCode()));
        QueryParamUtil.setBaseParamValue(param,userAccountVo);
        try {
            param.setEndDate(DateUtil.getMonthString());
            if ("".equals(param.getStartDate()) || null == param.getStartDate()) {
                param.setStartDate(DateUtil.getMonthString());
            }

            String nowMonth = DateUtil.sdf2.format(new Date()).substring(0,8)+"01";
            param.setNowMonth(nowMonth);
            page = suspendFamilyReadService.queryZanTingList(param, pageParam);
        } catch (Exception e) {
            log.error("救助家庭暂停异常" + e.getMessage());
            e.printStackTrace();
        }
        return page;
    }


    @Override
    public Page querySuspendList(BatchProtectParam param, UserAccountVo userAccountVo, PageParam pageParam) {
        QueryParamUtil.setBaseParamValue(param,userAccountVo);
        return suspendFamilyReadService.querySuspendList(param, pageParam);
    }


    @Override
    public BaseResult<Boolean> suspendFamily(ExpireFamilyParam param, UserAccountVo userAccountVo){
        BaseResult<Boolean> baseResult = new BaseResult<>();
        boolean isCounty = false;
        if(StringUtils.isNotBlank(param.getPrimaryKeys())){
            isCounty = true;
        }

        orderSuspendCareReadService.getExistSuspendOrderId(Arrays.asList(param.getIds().split(",")));
        BaseResult<Object> ob = this.checkSalaryDate(1, param.getIds(), null, param.getStopMonth(), isCounty);
        if(null != ob){
            List<OrderEntity> data = (List<OrderEntity>)ob.getData();
            if(CollectionUtils.isEmpty(data)){

                baseResult.setMsg(ob.getMsg());
                baseResult.setData(false);
                return baseResult;
            }else{

                if(data.size() <= 5){
                    return suspendMemberWriteService.suspendFamily(param, data, userAccountVo);
                }else{

                    applicationContext.publishEvent(new SuspendManageEvent(this,data,userAccountVo,param));
                }
            }
        }
        return null;
    }


    private BaseResult<Object> checkSalaryDate(int type,String ids,String startMonth,String endMonth,boolean isCounty){
        BaseResult<Object> result = new BaseResult<>();
        StringBuffer msg = new StringBuffer();
        switch (type){
            case 1:
                List<OrderEntity> list = orderReadService.queryOrderByIds(ids.split(","));
                if (CollectionUtils.isEmpty(list)) {
                    throw new BizException(FailureCode.ERR_10003);
                }






//                        Integer startDate = Integer.parseInt(order.getStartMonth().replaceAll("-", ""));

//                        if (!CommonUtil.invalidArgs(startDate) && ((Integer.valueOf(checkEndDate) - startDate)) <= 0) {
//                            msg = msg.append(order.getIdcard()).append(",");




                result.setMsg("身份证："+msg.toString()+"的数据的救助开始年月大于等于您选择的停止年月，停止年月请选择在" + endMonth + "之后");
                result.setData(list);
                break;
            case 2:

                List<SuspendFamilyResultDTO> suspendFaDtoList = suspendFamilyReadService.queryById(ids.split(","));
                if (CollectionUtils.isEmpty(suspendFaDtoList)) {
                    throw new BizException("-1", "要恢复状态的数据不能为空");
                }


                Iterator<SuspendFamilyResultDTO> iteratorSusp = suspendFaDtoList.iterator();



//                    if (Integer.parseInt(dto.getStartMonth().replaceAll("-", "")) - Integer.valueOf(DateUtil.getMonthString()) > 0) {
//                        msg = msg.append(dto.getIdCard()).append(",");




//                    if (Constant.SuspendState.RECOVERY.equals(dto.getState())) {


//                    //if (!CommonUtil.invalidArgs(order.getStartMonth()) && ((Integer.valueOf(endMonth)-Integer.valueOf(order.getStartMonth())))<0) {
//                    //msg = msg.append(order.getIdcard()).append(",");




                result.setMsg("身份证："+msg.toString()+"的数据暂停时间大于当月的不能恢复");
                result.setData(suspendFaDtoList);
                break;
            case 3:
                break;
        }
        return result;
    }


    @Override
    public BaseResult<Boolean> repealSuspend(String ids, UserAccountVo userAccountVo) {
        BaseResult<Boolean> result = new BaseResult<>();
        result.setData(false);

        List<SuspendFamilyResultDTO> suspendFaList = suspendFamilyReadService.queryById(ids.split(","));
        if (CollectionUtils.isEmpty(suspendFaList)) {
            throw new BizException(FailureCode.ERR_10003);
        }
        log.info("开始执行暂停家庭撤销动作----------》");

        List<String> familyIds = new ArrayList<>();
        for (SuspendFamilyResultDTO suspendFaDto : suspendFaList) {

            if (Integer.parseInt(suspendFaDto.getStartMonth()) - Integer.parseInt(DateUtil.getMonthString().replaceAll("-", "")) > 1) {
                throw new BizException("-1", "不能撤销当前月之前的暂停记录");
            }
            familyIds.add(suspendFaDto.getFamilyId());

            OrderEntity orderEntity = orderReadService.getOrderById(suspendFaDto.getOrderId());
            orderEntity.setStartMonth(DateUtil.getMonthString());

            fundPayReadService.verifyFundPayThrow(orderEntity.getBusinessType(), orderEntity.getCountyCode(),
                    orderEntity.getStandType(), DateUtil.getMonthString(), orderEntity.getSupplyType(),
                    Constant.FundType.CAPITAL_FUND_PAY);


            SuspendFamilyEntity entity = new SuspendFamilyEntity();
            entity.setId(suspendFaDto.getId());
            entity.setCancelDate(DateUtil.getTimestamp());
            if(Constant.UserLevel.COUNTY.equals(userAccountVo.getAreaLevel())){

                entity.setState(Constant.SuspendState.REVOKE);


                orderWriteService.modifyOrder(orderEntity, "", Constant.MAX_YEAR, null,Constant.SuspendState.REVOKE);


                familySalaryWriteService.updateEndDate(orderEntity.getOrderId(), Constant.MAX_YEAR);

                salaryChangeWriteService.insertSalaryChange(orderEntity, DateUtil.getMonthString(), "暂停撤销",Constant.SalaryChangeType.CHANGE_NO);

            }else if(Constant.UserLevel.STREET.equals(userAccountVo.getAreaLevel())){
                entity.setState(Constant.SuspendState.S_REVOKE);
            }
            suspendFamilyWriteService.updateIgnoreNull(entity);

        }
        return result;
    }


    @Override
    public BaseResult<Boolean> recoverySuspend(SuspendFamilyResultParam param, UserAccountVo userAccountVo) {
        BaseResult<Boolean> result = new BaseResult<>();
        BaseResult<Object> ob = this.checkSalaryDate(2, param.getIds(), null, param.getEndMonth(), false);
        List<SuspendFamilyResultDTO> suspendFaDtoList = (List<SuspendFamilyResultDTO>)ob.getData();

        //List<SuspendFamilyResultDTO> suspendFaDtoList = suspendFamilyReadService.queryById(param.getIds().split(","));
        if (CollectionUtils.isEmpty(suspendFaDtoList)) {
            if(StringUtils.isEmpty(ob.getMsg())){
                throw new BizException("-1", "要恢复状态的数据不能为空");
            }else{
                throw new BizException("-1", ob.getMsg());
            }
        }
        for (SuspendFamilyResultDTO suspendFaDto : suspendFaDtoList) {

            List<OrderEntity> list = orderReadService.queryOrderByIds(suspendFaDto.getOrderId().split(","));

            if(Constant.UserLevel.COUNTY.equals(userAccountVo.getAreaLevel())){

                if(!CollectionUtils.isEmpty(list)){
                    OrderEntity oe = list.get(0);

                    fundPayReadService.verifyFundPayThrow(oe.getBusinessType(), oe.getCountyCode(),
                            oe.getStandType(), param.getEndMonth(), oe.getSupplyType(), Constant.FundType.CAPITAL_FUND_PAY);
                }else{
                    throw new BizException("-1", "暂停数据异常");
                }

                SuspendFamilyEntity entity = new SuspendFamilyEntity();
                entity.setState(Constant.SuspendState.N_RECOVERY);
                if("1".equals(param.getCheckOption())){

                    BigDecimal familySalaryMoney = BigDecimal.ZERO;
                    BigDecimal memberSalaryNumber = BigDecimal.ZERO;

                    entity.setState(Constant.SuspendState.RECOVERY);
                    entity.setReissueMoney(familySalaryMoney.doubleValue());
                    int month = 0;
                    if("1".equals(param.getIsReissue())){
                        try {

                            month = dayCompare(suspendFaDto.getStartMonth(), param.getEndMonth());

                        } catch (ParseException e) {
                            log.error(e.getMessage());
                        }
                    }

                    OrderEntity orderEntity = orderReadService.getOrderById(suspendFaDto.getOrderId());

                    fundPayReadService.verifyFundPayThrow(orderEntity.getBusinessType(), orderEntity.getCountyCode(),
                            orderEntity.getStandType(), param.getEndMonth(), orderEntity.getSupplyType(),
                            Constant.FundType.CAPITAL_FUND_PAY);

                    String newOrderId = Constant.getUUID();
                    String oldOrderId = suspendFaDto.getOrderId();
                    orderEntity.setSourOrderId(oldOrderId);
                    orderEntity.setOrderId(newOrderId);

                    orderWriteService.modifyOrder(orderEntity, param.getEndMonth(),Constant.MAX_YEAR,userAccountVo, Constant.SuspendState.RECOVERY);

                    log.info("开始执行待遇保存 参数{}" + JSON.toJSONString(suspendFaDto));


                    saveMemberHistory(param.getEndMonth(),Constant.MAX_YEAR, oldOrderId, newOrderId,false);

                    FamilySalaryEntity oldFamilySalary =
                            familySalaryReadService.getFamilySumSalaryByOrderId(oldOrderId);
                    List<MemberSalaryEntity> newMemberSalarys =
                            familyMemberSalaryReadService.queryMemberSumSalaryByOrderId(oldOrderId);
                    log.info("开始执行家庭待遇表保存 参数:{}" + JSON.toJSONString(oldFamilySalary));
                    familyMemberSalaryWriteService.reSalaryMember(oldFamilySalary, newMemberSalarys, param.getEndMonth()+"01",Constant.MAX_YEAR+"01", newOrderId,false);

                    if (suspendFaDto.getStartMonth().equals(param.getEndMonth())) {
                        salaryChangeWriteService.insertSalaryChange(oldFamilySalary, newMemberSalarys, param.getEndMonth(),
                                "暂停恢复", orderEntity, Constant.SalaryChangeType.CANCEL_SUSPEND);
                    } else {
                        salaryChangeWriteService.insertSalaryChange(oldFamilySalary, newMemberSalarys, param.getEndMonth(),
                                "暂停恢复", orderEntity, Constant.SalaryChangeType.CANCEL_SUSPEND);
                    }


                    if(month > 0){


                        FamilySalaryEntity familySalaryEntity =
                                familySalaryReadService.getFamilySumSalaryByOrderId(suspendFaDto.getOrderId());

                        List<FamilyMemberEntity> memberList = familyMemberReadService.queryHistoryInfo(suspendFaDto.getOrderId());

                        if (CollectionUtils.isNotEmpty(memberList) && !CommonUtil.invalidArgs(familySalaryEntity)) {
                            familySalaryMoney =
                                    BigDecimal.valueOf(familySalaryEntity.getSalaryNumber()).multiply(BigDecimal.valueOf(month)).setScale(2, BigDecimal.ROUND_HALF_UP);
                            memberSalaryNumber = familySalaryMoney.divide(BigDecimal.valueOf(memberList.size()), 2,
                                    BigDecimal.ROUND_HALF_UP).setScale(2,
                                    BigDecimal.ROUND_HALF_UP);
                        }
                        if (BigDecimal.ZERO.compareTo(memberSalaryNumber) < 0) {

                            familyMemberSalaryWriteService.reSalaryMember(oldFamilySalary, newMemberSalarys, param.getReissueMonth()+"01",param.getReissueMonth()+"01", newOrderId,true);
                        }
                    }
                }


                entity.setId(suspendFaDto.getId());
                entity.setEndMonth(param.getEndMonth());
                entity.setReissueMonth(param.getReissueMonth());
                entity.setIsReissue(param.getIsReissue());
                //entity.setEndMonth(param.getEndMonth());
                //entity.setRemark(param.getRemark());
                //entity.setReissueMonth(param.getReissueMonth());


                log.info("开始更新暂停数据 参数:{}" + JSON.toJSONString(entity));
                suspendFamilyWriteService.updateIgnoreNull(entity);

                SuspendApproveEntity approveEntity = new SuspendApproveEntity();
                approveEntity.setId(Constant.getUUID());
                approveEntity.setCheckOpinion(param.getCheckOption());
                approveEntity.setCheckResult(param.getCheckResult());
                approveEntity.setCheckPeople(userAccountVo.getUsername());
                approveEntity.setCheckType(Constant.SuspendApproveType.SUSPEND_R);
                approveEntity.setOperator(userAccountVo.getUserId());
                approveEntity.setOperatorDate(new Date());
                approveEntity.setOrgId(userAccountVo.getOrgId());
                approveEntity.setSuspendId(suspendFaDto.getId());
                suspendApproveWriteService.insertIgnoreNull(approveEntity);

            }else if(Constant.UserLevel.STREET.equals(userAccountVo.getAreaLevel())){

                SuspendFamilyEntity entity = new SuspendFamilyEntity();
                entity.setId(suspendFaDto.getId());
                entity.setEndMonth(param.getEndMonth());
                entity.setProcesExplan(param.getRemark());
                entity.setReissueMonth(param.getReissueMonth());
                entity.setIsReissue(param.getIsReissue());
                entity.setState(Constant.SuspendState.S_RECOVERY);
                log.info("开始更新暂停数据 参数:{}" + JSON.toJSONString(entity));
                suspendFamilyWriteService.updateIgnoreNull(entity);
            }
        }
        //familyMemberWriteService.batchUpdateStateByFamilyIds(Constant.PeopleState.SUSPEND_STATE,familyIds);
        return result;
    }

    @Override
    public BaseResult<Boolean> terminationSuspend(SuspendFamilyResultParam param, UserAccountVo userAccountVo) {

        dateTime = LocalDateTime.now();
        DateTimeFormatter dtf2 = DateTimeFormatter.ofPattern("yyyyMM");
        String strDate2 = dtf2.format(dateTime);
        param.setEndMonth(strDate2);

        List<SuspendFamilyResultDTO> suspendFaDtoList = suspendFamilyReadService.queryById(param.getIds().split(","));
        if (CollectionUtils.isEmpty(suspendFaDtoList)) {
            throw new BizException("-1", "要终止救助的对象不能为空");
        }
        List<String> familyIds = new ArrayList<>();
        BatchExpireDTO exDto = new BatchExpireDTO();
        exDto.setStopMonth(param.getEndMonth());
        exDto.setApprovalDate(new Date());
        exDto.setRemark(param.getRemark());
        exDto.setBusinessType(param.getBusinessType());
        exDto.setOperator(userAccountVo.getLoginId());
        exDto.setPrincipal(userAccountVo.getLoginId());
        List<String> selectedRowKeys = new ArrayList<>();
        for (SuspendFamilyResultDTO suspendFaDto : suspendFaDtoList) {
            SuspendFamilyEntity entity = new SuspendFamilyEntity();

            familyIds.add(suspendFaDto.getFamilyId());
            selectedRowKeys.add(suspendFaDto.getOrderId());
            entity.setId(suspendFaDto.getId());
            entity.setStopReason(param.getRemark());
            if(Constant.UserLevel.COUNTY.equals(userAccountVo.getAreaLevel())){

                entity.setState(Constant.SuspendState.STOP);
                if("0".equals(param.getCheckOption())){
                    entity.setState(Constant.SuspendState.N_STOP);
                }

                SuspendApproveEntity approveEntity = new SuspendApproveEntity();
                approveEntity.setId(Constant.getUUID());
                approveEntity.setCheckOpinion(param.getCheckOption());
                approveEntity.setCheckResult(param.getCheckResult());
                approveEntity.setCheckPeople(userAccountVo.getUsername());
                approveEntity.setCheckType(Constant.SuspendApproveType.SUSPEND_E);
                approveEntity.setOperator(userAccountVo.getUserId());
                approveEntity.setOperatorDate(new Date());
                approveEntity.setOrgId(userAccountVo.getOrgId());
                approveEntity.setSuspendId(suspendFaDto.getId());
                suspendApproveWriteService.insertIgnoreNull(approveEntity);
            }else if(Constant.UserLevel.STREET.equals(userAccountVo.getAreaLevel())){
                entity.setState(Constant.SuspendState.S_STOP);
            }
            log.info("开始更新暂停数据 参数:{}" + JSON.toJSONString(entity));
            suspendFamilyWriteService.updateIgnoreNull(entity);

        }
        if(Constant.UserLevel.COUNTY.equals(userAccountVo.getAreaLevel())){
            if("1".equals(param.getCheckOption())){
                exDto.setSelectedRowKeys(selectedRowKeys.stream().toArray(String[]::new));
                expireSalvationService.batchExpire(exDto,userAccountVo,Constant.SuspendApproveType.SUSPEND_E);
            }
        }
        BaseResult<Boolean> result = new BaseResult<>();
        return result;
    }


    public void saveMemberHistory(String startMonth,String stopMonth,  String oldOrderId, String newOrderId,boolean isSavaSalay) {
        if(!isSavaSalay){
            List<FamilyMemberHistoryEntity> familyMemberHistoryEntities =
                    familyMemberHistoryReadService.queryByOrderId(oldOrderId);
            FamilyMainHistoryEntity familyMainHistoryEntity =
                    familyMainHistoryReadService.getByOrderIdState(oldOrderId);
            if (ObjectUtil.isEmpty(familyMainHistoryEntity)) {
                familyMainHistoryEntity = new FamilyMainHistoryEntity();

                familyMainHistoryEntity.setFamilyNumber(familyMemberHistoryEntities.size());
            }
            familyMemberHistoryWriteService.rescoverMemberHistoryEntity(familyMainHistoryEntity,
                    familyMemberHistoryEntities, newOrderId);
        }

    }

    private int dayCompare(String fromDate, String toDate) throws ParseException {

        Date sdate = new SimpleDateFormat("yyyyMMdd").parse(fromDate + "01");
        String strDate1 = new SimpleDateFormat("yyyy-MM-dd").format(sdate);

        Date edate = new SimpleDateFormat("yyyyMMdd").parse(toDate + "01");
        String etrDate1 = new SimpleDateFormat("yyyy-MM-dd").format(edate);

        Date startDate = new SimpleDateFormat("yyyy-MM-dd").parse(strDate1);
        Date endDate = new SimpleDateFormat("yyyy-MM-dd").parse(etrDate1);
        Calendar from = Calendar.getInstance();
        from.setTime(startDate);
        Calendar to = Calendar.getInstance();
        to.setTime(endDate);

        int fromYear = from.get(Calendar.YEAR);
        int fromMonth = from.get(Calendar.MONTH);
        int toYear = to.get(Calendar.YEAR);
        int toMonth = to.get(Calendar.MONTH);

        //int day = (int) ((to.getTimeInMillis()  -  from.getTimeInMillis())  /  (24  *  3600  *  1000));
        return toYear * 12 + toMonth - (fromYear * 12 + fromMonth);
    }


    @Override
    public Map<String,String> findFundPayDate(String orderId,String selectType){
        Map<String,String> res = new HashMap<>();
        res.put("msg","FAIL");
        res.put("data","");
        String now = DateUtil.getMonthString();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        SimpleDateFormat sdf1 = new SimpleDateFormat("yyyyMM");
        try{
            List<OrderEntity> list = orderReadService.queryOrderByIds(orderId.split(","));
            if(CollectionUtils.isEmpty(list)){
                throw new BizException(FailureCode.ERR_10003);
            }
            OrderEntity orderEntity = list.get(0);

            String s;
            if("1".equals(selectType)){
                s = fundPayReadService.verifyFundPay(orderEntity.getBusinessType(), orderEntity.getCountyCode(),
                        orderEntity.getStandType(), now, orderEntity.getSupplyType(), Constant.FundType.CAPITAL_FUND_PAY,"1");

            }else{

                s = fundPayReadService.verifySuspendFundPay(orderEntity.getOrderId(),orderEntity.getBusinessType(),orderEntity.getCountyCode(),
                        orderEntity.getStandType(),now,orderEntity.getSupplyType());
            }
            if(StringUtils.isNotBlank(s)){

                Date date = DateUtil.str2Date(s, sdf);
                Calendar cal = Calendar.getInstance();
                cal.setTime(date);
                cal.add(Calendar.MONTH, 1);
                String dateStr = sdf1.format(cal.getTime());

                Date parse = new SimpleDateFormat("yyyy-MM-dd").parse(s);
                String dateString = sdf1.format(parse);

                res.put("msg","SUCCESS");
                res.put("new",dateStr);
                res.put("old",dateString);
                return res;
            }else{
                String saveDate = now+"01";
                Date parse = new SimpleDateFormat("yyyyMMdd").parse(saveDate);
                String dateString = sdf1.format(parse);




//                cal.add(Calendar.MONTH, 1);
//                String dateStr = sdf.format(cal.getTime());
                res.put("new",dateString);
                return res;
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        return res;

    }


    @Override
    public String  houseHoldQuit(String id,UserAccountVo accountVo){

        List<SuspendFamilyResultDTO> suspendList = suspendFamilyReadService.queryById(new String[]{id});
        if(!CommonUtil.invalidArgs(suspendList) && suspendList.size()>0){
            if(!suspendList.get(0).getState().equals(Constant.SuspendState.SUSPEND) && !suspendList.get(0).getState().equals(Constant.SuspendState.N_RECOVERY)){
                throw new BizException("-1","请选择一条已暂停的数据");
            }
            SuspendFamilyResultDTO suspendFamily = suspendList.get(0);

            OrderEntity orderEntity = orderReadService.getById(suspendFamily.getOrderId());
            if(Constant.OrderType.NEW.equals(orderEntity.getType())){
                String checkDate = DateUtil.sdf2.format(orderEntity.getCheckDate()).substring(0,7);
                String nowMonth = DateUtil.sdf2.format(new Date()).substring(0,7);
                if(nowMonth.equals(checkDate)){
                    throw new BizException("-1","该家庭为当月新增在保家庭，当月不能整户停保，如果一定要停保请向区县申请删除该家庭的新申请业务信息");
                }
            }

            Integer nowMonth = Integer.valueOf(DateUtil.sdfYM.format(new Date()));
            Integer suspendMonth = Integer.valueOf(suspendFamily.getStartMonth());
            if(nowMonth-suspendMonth<0){
                throw new BizException("-1","本次业务暂停年月为"+suspendMonth+"，请在暂停生效后操作");
            }

            String newOrderId = recheckService.addRecheckOrder(suspendFamily.getOrderId(),accountVo);

            OrderEntity entity = new OrderEntity();
            entity.setOrderId(newOrderId);
            entity.setSuspendFlag(Constant.SuspendFlag.NORMAL_STATE);
            orderWriteService.updateIgnoreNull(entity);

            salvationApplyService.houseHoldSuspend(newOrderId,suspendFamily.getFamilyId());

            SuspendFamilyEntity familyEntity = new SuspendFamilyEntity();
            familyEntity.setId(suspendFamily.getId());
            familyEntity.setState(Constant.SuspendState.S_STOP);
            suspendFamilyWriteService.updateIgnoreNull(familyEntity);
            return "success";
        }else {
            return "fail";
        }
    }
}
